<template>
  <div style="padding: 20px">
    <el-card>
      <el-form :model="personnelData" inline label-width="100px">
        <el-form-item label="id">
          <el-input
            v-model="personnelData.id"
            placeholder="请输入ID"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="personnelData.name"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input
            v-model="personnelData.age"
            placeholder="请输入年龄"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="personnelData.sex"
            placeholder="请选择性别"
            clearable
          >
            <el-option
              v-for="item in sexList"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-row>
        <el-col :span="18"
          ><el-button
            type="success"
            @click="createMember"
            style="margin-left: 100px"
            >新建</el-button
          >
        </el-col>
        <el-col :span="6"
          ><el-button type="primary" @click="query">查询</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card style="margin-top: 20px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="会员数据" name="tableData">
          <el-button type="primary" @click="exportExcel">导出</el-button>
          <el-table
            :data="tableData.slice((page - 1) * pageSize, page * pageSize)"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="180">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="age" label="年龄"> </el-table-column>
            <el-table-column prop="sex" label="性别"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="updateMember(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="deleteMember(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
          >
          </el-pagination
        ></el-tab-pane>
        <el-tab-pane label="可视化" name="echarts">
          <div id="age" style="height: 500px"></div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="create_member_status + '会员信息'"
      :visible.sync="create_member_show"
      width="30%"
    >
      <el-form
        :model="create_member_data"
        ref="create_member_data"
        label-width="80px"
        :rules="rules"
        inline
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="create_member_data.name"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="create_member_data.age"
            placeholder="请输入年龄"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="create_member_data.sex"
            placeholder="请选择性别"
            clearable
          >
            <el-option
              v-for="item in sexList"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitCreateMember('create_member_data')"
        >
          {{
            create_member_status === "新建" ? "确 定" : "确认关闭窗口"
          }}</el-button
        >
      </span>
    </el-dialog>
    <!-- <WLCakeShopMember
      v-model="create_member_data"
      :create_member_show="create_member_show"
      :sexList="sexList"
      :rules="rules"
    ></WLCakeShopMember> -->
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import XLSX from "xlsx";
// import WLCakeShopMember from "./WLCakeShopMember";
// import WLCakeShopMember from "@/components/WLCakeShopMember/WLCakeShopMember.vue";
export default {
  //   mixins: [WLCakeShopMember],

  data() {
    return {
      personnelData: {
        id: "",
        name: "",
        age: "",
        sex: "",
      },
      sexList: [
        { label: "男", value: "男" },
        { label: "女", value: "女" },
        { label: "其他", value: "其他" },
      ],
      //创建
      create_member_show: false,
      create_member_data: {},
      create_member_status: "新建",
      //选项卡
      activeName: "echarts",
      //表格相关
      tableData: [],
      page: 1,
      pageSize: 10,
      count: 0,
      //验证
      rules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
      },
    };
  },
  mounted() {
    //页面初始化
    this.init();
    let params = [
      { value: 10, name: "男" },
      { value: 20, name: "女" },
    ];
    this.initEcharts(params, "age");
  },
  // components: {
  //   WLCakeShopMember,
  // },
  methods: {
    //页面初始化
    init() {
      this.tableData =
        JSON.parse(window.localStorage.getItem("WLCakeShopMember")) || [];
    },
    //echarts初始化
    initEcharts(data, id) {
      var chartDom = document.getElementById(id);
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: "会员性别分布",
          // subtext: "Fake Data",
          left: "center",
        },
        tooltip: {
          trigger: "item",
          // formatter: "{a}<br/>{b}:{c},{d}",
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            name: "性别",
            type: "pie",
            radius: "50%",
            label: {
              normal: {
                formatter: "{b}: {d}%",
              },
            },
            data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      option && myChart.setOption(option);
    },

    //查询
    query() {
      this.$message.error("测试中功能");
    },
    //点击新建
    createMember() {
      this.create_member_show = true;
      this.create_member_status = "新建";
      this.create_member_data = {};
    },
    //点击编辑
    updateMember(row) {
      this.create_member_show = true;
      this.create_member_status = "更新";
      this.create_member_data = row;
    },
    //导出
    exportExcel() {
      //处理数据 将表格每条数据的key改为中文
      let tableData = [];
      for (let item of this.tableData) {
        //映射表
        let mapInfo = {
          id: "ID",
          name: "姓名",
          age: "年龄",
          sex: "性别",
        };

        let obj = {};
        let keys = Object.keys(mapInfo);
        for (let itemTow of keys) {
          let enKey = mapInfo[itemTow];
          obj[enKey] = item[itemTow];
        }
        tableData.push(obj);
      }

      // 新建空workbook，然后加入worksheet
      const ws = XLSX.utils.json_to_sheet(tableData);
      // 设置每列的列宽，10代表10个字符，注意中文占2个字符
      let arr = [];
      for (let item of tableData) {
        arr.push({ wch: 10 });
      }
      ws["!cols"] = arr;
      // 新建book
      const wb = XLSX.utils.book_new();
      // 生成xlsx文件(book,sheet数据,sheet命名)
      XLSX.utils.book_append_sheet(wb, ws, "数据详情");
      // 写文件(book,xlsx文件名称)
      XLSX.writeFile(wb, "列表详情.xlsx");
    },
    //确定创建/更新会员信息
    submitCreateMember(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.create_member_status === "新建") {
            //给表格增加数据
            this.tableData.push({
              id:
                this.tableData.length === 0
                  ? 1
                  : this.tableData[this.tableData.length - 1].id + 1,
              ...this.create_member_data,
            });
            //重置表单
            this.$refs[formName].resetFields();
          }
          //关闭弹框
          this.create_member_show = false;
        }
      });
    },
    //删除
    deleteMember(id) {
      this.tableData.forEach((item, index) => {
        if (item.id == id) {
          this.tableData.splice(index, 1);
        }
      });

      this.$message.success("id:" + id + "删除成功");
    },
    //表格分页器
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.page = val;
    },
    //选项卡事件
    handleClick(tab, event) {
      console.log(tab, event);
    },
  },
  watch: {
    tableData: {
      deep: true,
      handler(newValue) {
        //将数据保存在本地localStorage
        window.localStorage.setItem(
          "WLCakeShopMember",
          JSON.stringify(newValue)
        );
        let arr = [
          { value: 0, name: "男" },
          { value: 0, name: "女" },
          { value: 0, name: "其他" },
        ];

        for (let item of newValue) {
          if (item.sex === "男") {
            arr[0].value++;
          } else if (item.sex === "女") {
            arr[1].value++;
          } else {
            arr[2].value++;
          }
        }
        this.initEcharts(arr, "age");
      },
    },
  },
};
</script>

<style>
</style>